package com.kuding.sts;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.kuding.exceptions.VinusException;
import com.kuding.props.AliyunSTSProperty;
import com.kuding.props.RamRoleFunction;

public class StsComponent {

	private AliyunSTSProperty aliyunSTSProperty;

	public StsComponent(AliyunSTSProperty aliyunSTSProperty) {
		this.aliyunSTSProperty = aliyunSTSProperty;
	}

	public AssumeRoleResponse createStsAccess(RamRoleFunction ramRoleFunction) {
		switch (ramRoleFunction) {
		case OSS:
			return createStsOssAccess();
		default:
			return null;
		}
	}

	private AssumeRoleResponse createStsOssAccess() {
		DefaultProfile.addEndpoint("", "Sts", aliyunSTSProperty.getEndPoint());
		DefaultProfile profile = DefaultProfile.getProfile("", aliyunSTSProperty.getAccessKeyId(),
				aliyunSTSProperty.getSecret());
		DefaultAcsClient client = new DefaultAcsClient(profile);
		final AssumeRoleRequest request = new AssumeRoleRequest();
		request.setMethod(MethodType.POST);
		request.setRoleArn(aliyunSTSProperty.getRoleArns().get(RamRoleFunction.OSS));
		request.setRoleSessionName(aliyunSTSProperty.getRoleSessionName());
		request.setDurationSeconds(aliyunSTSProperty.getExpireTime().getSeconds());
		try {
			final AssumeRoleResponse response = client.getAcsResponse(request);
			return response;
		} catch (ClientException e) {
			throw new VinusException("创建临时授权账号失败", e);
		}
	}
}
